home *** CD-ROM | disk | FTP | other *** search
/ PC Format (PL) 2008 February / PC_Format_022008.iso / Internet / Mozilla Thunderbird wtyczki / lightning-0.7-tb-win.xpi / js / calWcapUtils.js < prev    next >
Encoding:
JavaScript  |  2007-09-19  |  10.8 KB  |  323 lines

  1. /* -*- Mode: javascript; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  2. /* ***** BEGIN LICENSE BLOCK *****
  3.  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  4.  *
  5.  * The contents of this file are subject to the Mozilla Public License Version
  6.  * 1.1 (the "License"); you may not use this file except in compliance with
  7.  * the License. You may obtain a copy of the License at
  8.  * http://www.mozilla.org/MPL/
  9.  *
  10.  * Software distributed under the License is distributed on an "AS IS" basis,
  11.  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  12.  * for the specific language governing rights and limitations under the
  13.  * License.
  14.  *
  15.  * The Original Code is Sun Microsystems code.
  16.  *
  17.  * The Initial Developer of the Original Code is
  18.  * Sun Microsystems, Inc.
  19.  * Portions created by the Initial Developer are Copyright (C) 2007
  20.  * the Initial Developer. All Rights Reserved.
  21.  *
  22.  * Contributor(s):
  23.  *   Daniel Boelzle <daniel.boelzle@sun.com>
  24.  *
  25.  * Alternatively, the contents of this file may be used under the terms of
  26.  * either the GNU General Public License Version 2 or later (the "GPL"), or
  27.  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  28.  * in which case the provisions of the GPL or the LGPL are applicable instead
  29.  * of those above. If you wish to allow use of your version of this file only
  30.  * under the terms of either the GPL or the LGPL, and not to allow others to
  31.  * use your version of this file under the terms of the MPL, indicate your
  32.  * decision by deleting the provisions above and replace them with the notice
  33.  * and other provisions required by the GPL or the LGPL. If you do not delete
  34.  * the provisions above, a recipient may use your version of this file under
  35.  * the terms of any one of the MPL, the GPL or the LGPL.
  36.  *
  37.  * ***** END LICENSE BLOCK ***** */
  38.  
  39. var g_bShutdown = false;
  40. var g_logTimezone = null;
  41. var g_logFilestream = null;
  42. var g_logPrefObserver = null;
  43.  
  44. function initLogging()
  45. {
  46.     g_logTimezone = getPref("calendar.timezone.local", null);
  47.     
  48.     if (g_logFilestream) {
  49.         try {
  50.             g_logFilestream.close();
  51.         }
  52.         catch (exc) {
  53.         }
  54.         g_logFilestream = null;
  55.     }
  56.     
  57.     LOG_LEVEL = getPref("calendar.wcap.log_level", 0);
  58.     if (LOG_LEVEL < 1 && getPref("calendar.debug.log", false))
  59.         LOG_LEVEL = 1; // at least basic logging when calendar.debug.log is set
  60.     
  61.     if (LOG_LEVEL > 0) {
  62.         var logFileName = getPref("calendar.wcap.log_file", null);
  63.         if (logFileName) {
  64.             try {
  65.                 // set up file:
  66.                 var logFile = Components.classes["@mozilla.org/file/local;1"]
  67.                                         .createInstance(Components.interfaces.nsILocalFile);
  68.                 logFile.initWithPath(logFileName);
  69.                 // create output stream:
  70.                 var logFileStream =
  71.                     Components.classes["@mozilla.org/network/file-output-stream;1"]
  72.                               .createInstance(Components.interfaces.nsIFileOutputStream);
  73.                 logFileStream.init(
  74.                     logFile,
  75.                     0x02 /* PR_WRONLY */ |
  76.                     0x08 /* PR_CREATE_FILE */ |
  77.                     (getPref("calendar.wcap.log_file_append", false)
  78.                      ? 0x10 /* PR_APPEND */ : 0x20 /* PR_TRUNCATE */),
  79.                     0700 /* read, write, execute/search by owner */,
  80.                     0 /* unused */);
  81.                 g_logFilestream = logFileStream;
  82.             }
  83.             catch (exc) {
  84.                 logError(exc, "init logging");
  85.             }
  86.         }
  87.         log("################################# NEW LOG (0.5) #################################",
  88.             "init logging");
  89.     }
  90.     if (!g_logPrefObserver) {
  91.         g_logPrefObserver = { // nsIObserver:
  92.             observe: function logPrefObserver_observe(subject, topic, data) {
  93.                 if (topic == "nsPref:changed") {
  94.                     switch (data) {
  95.                     case "calendar.wcap.log_level":
  96.                     case "calendar.wcap.log_file":
  97.                     case "calendar.debug.log":
  98.                         initLogging();
  99.                         break;
  100.                     }
  101.                 }
  102.             }
  103.         };
  104.         var prefBranch = Components.classes["@mozilla.org/preferences-service;1"]
  105.                                    .getService(Components.interfaces.nsIPrefBranch2);
  106.         prefBranch.addObserver("calendar.wcap.log_level", g_logPrefObserver, false);
  107.         prefBranch.addObserver("calendar.wcap.log_file", g_logPrefObserver, false);
  108.         prefBranch.addObserver("calendar.debug.log", g_logPrefObserver, false);
  109.         
  110.         var observerService = Components.classes["@mozilla.org/observer-service;1"]
  111.                                         .getService(Components.interfaces.nsIObserverService);
  112.         var appObserver = { // nsIObserver:
  113.             observe: function app_observe(subject, topic, data) {
  114.                 if (topic == "quit-application")
  115.                     prefBranch.removeObserver("calendar.", g_logPrefObserver);
  116.             }
  117.         };
  118.         observerService.addObserver(appObserver, "quit-application", false);
  119.     }
  120. }
  121.  
  122. function log(msg, context, bForce)
  123. {
  124.     if (bForce || LOG_LEVEL > 0) {
  125.         var ret = "";
  126.         if (context)
  127.             ret += ("[" + context + "]");
  128.         if (ret.length > 0)
  129.             ret += "\n";
  130.         ret += msg;
  131.         var now = getTime();
  132.         if (now && g_logTimezone)
  133.             now = now.getInTimezone(g_logTimezone);
  134.         var str = ("### WCAP log entry: " + now + "\n" + ret);
  135.         getConsoleService().logStringMessage(str);
  136.         str = ("\n" + str + "\n");
  137.         dump(str);
  138.         if (g_logFilestream) {
  139.             try {
  140.                 // xxx todo?
  141.                 // assuming ANSI chars here, for logging sufficient:
  142.                 g_logFilestream.write(str, str.length);
  143.             }
  144.             catch (exc) { // catching any io errors here:
  145.                 var err = ("error writing log file: " + errorToString(exc));
  146.                 Components.utils.reportError(exc);
  147.                 getConsoleService().logStringMessage(err);
  148.                 dump(err  + "\n\n");
  149.             }
  150.         }
  151.         return ret;
  152.     }
  153.     else
  154.         return msg;
  155. }
  156.  
  157. function logWarning(err, context)
  158. {
  159.     var msg = errorToString(err);
  160.     var scriptError = Components.classes["@mozilla.org/scripterror;1"]
  161.                                 .createInstance(Components.interfaces.nsIScriptError);
  162.     scriptError.init(log("warning: " + msg, context, true),
  163.                      null, null, 0, 0,
  164.                      Components.interfaces.nsIScriptError.warningFlag,
  165.                      "component javascript");
  166.     getConsoleService().logMessage(scriptError);
  167.     return msg;
  168. }
  169.  
  170. function logError(err, context)
  171. {
  172.     var msg = errorToString(err);
  173.     Components.utils.reportError( log("error: " + msg, context, true) );
  174.     return msg;
  175. }
  176.  
  177. // late-inited service accessors:
  178.  
  179. var g_consoleService = null;
  180. function getConsoleService() {
  181.     if (!g_consoleService) {
  182.         g_consoleService =
  183.             Components.classes["@mozilla.org/consoleservice;1"]
  184.                       .getService(Components.interfaces.nsIConsoleService);
  185.     }
  186.     return g_consoleService;
  187. }
  188.  
  189. var g_windowWatcher = null;
  190. function getWindowWatcher() {
  191.     if (!g_windowWatcher) {
  192.         g_windowWatcher =
  193.             Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  194.                       .getService(Components.interfaces.nsIWindowWatcher);
  195.     }
  196.     return g_windowWatcher;
  197. }
  198.  
  199. var g_icsService = null;
  200. function getIcsService() {
  201.     if (!g_icsService) {
  202.         g_icsService =
  203.             Components.classes["@mozilla.org/calendar/ics-service;1"]
  204.                       .getService(Components.interfaces.calIICSService);
  205.     }
  206.     return g_icsService;
  207. }
  208.  
  209. var g_fbService = null;
  210. function getFreeBusyService() {
  211.     if (!g_fbService) {
  212.         g_fbService =
  213.             Components.classes["@mozilla.org/calendar/freebusy-service;1"]
  214.                       .getService(Components.interfaces.calIFreeBusyService);
  215.     }
  216.     return g_fbService;
  217. }
  218.  
  219. var g_domParser = null;
  220. function getDomParser() {
  221.     if (!g_domParser) {
  222.         g_domParser =
  223.             Components.classes["@mozilla.org/xmlextras/domparser;1"]
  224.                       .getService(Components.interfaces.nsIDOMParser);
  225.     }
  226.     return g_domParser;
  227. }
  228.  
  229. function subClass(subCtor, baseCtor) {
  230.     subCtor.prototype = new baseCtor();
  231.     subCtor.prototype.constructor = subCtor;
  232.     subCtor.prototype.superClass = baseCtor;
  233. }
  234.  
  235. function isParent(item) {
  236.     if (item.id != item.parentItem.id) {
  237.         throw new Components.Exception("proxy has different id than its parent!");
  238.     }
  239.     return (!item.recurrenceId);
  240. }
  241.  
  242. function forEachIcalComponent(icalRootComp, componentType, func, maxResults)
  243. {
  244.     var itemCount = 0;
  245.     // libical returns the vcalendar component if there is just
  246.     // one vcalendar. If there are multiple vcalendars, it returns
  247.     // an xroot component, with those vcalendar childs. We need to
  248.     // handle both.
  249.     for ( var calComp = (icalRootComp.componentType == "VCALENDAR"
  250.                          ? icalRootComp
  251.                          : icalRootComp.getFirstSubcomponent("VCALENDAR"));
  252.           calComp != null && (!maxResults || itemCount < maxResults);
  253.           calComp = icalRootComp.getNextSubcomponent("VCALENDAR") )
  254.     {
  255.         for ( var subComp = calComp.getFirstSubcomponent(componentType);
  256.               subComp != null && (!maxResults || itemCount < maxResults);
  257.               subComp = calComp.getNextSubcomponent(componentType) )
  258.         {
  259.             func( subComp );
  260.             ++itemCount;
  261.         }
  262.     }
  263. }
  264.  
  265. function filterXmlNodes(name, rootNode)
  266. {
  267.     var ret = [];
  268.     if (rootNode) {
  269.         var nodeList = rootNode.getElementsByTagName(name);
  270.         for (var i = 0; i < nodeList.length; ++i) {
  271.             var node = nodeList.item(i);
  272.             ret.push( trimString(node.textContent) );
  273.         }
  274.     }
  275.     return ret;
  276. }
  277.  
  278. function trimString(str) {
  279.     return str.replace(/(^\s+|\s+$)/g, "");
  280. }
  281.  
  282. function getTime() {
  283.     if (g_bShutdown)
  284.         return null;
  285.     var ret = new CalDateTime();
  286.     ret.jsDate = new Date();
  287.     return ret;
  288. }
  289.  
  290. function getIcalUTC(dt) {
  291.     if (!dt || !dt.isValid)
  292.         return "0";
  293.     else {
  294.         var dtz = dt.timezone;
  295.         if (dtz == "UTC" || dtz == "floating")
  296.             return dt.icalString;
  297.         else
  298.             return dt.getInTimezone("UTC").icalString;
  299.     }
  300. }
  301.  
  302. function getDatetimeFromIcalString(val) {
  303.     if (!val || val.length == 0 || val == "0")
  304.         return null;
  305.     // assuming timezone is known:
  306.     var dt = new CalDateTime();
  307.     dt.icalString = val;
  308.     return dt;
  309. }
  310.  
  311. function getDatetimeFromIcalProp(prop) {
  312.     if (!prop)
  313.         return null;
  314.     return getDatetimeFromIcalString(prop.valueAsIcalString);
  315. }
  316.  
  317. function getPref(prefName, defaultValue) {
  318.     var ret = getPrefSafe(prefName, defaultValue);
  319.     log(ret, "getPref(): prefName=" + prefName);
  320.     return ret;
  321. }
  322.  
  323.